package com.apestech.framework.dictionary.lib;

import com.apestech.framework.db.SqlResultSet;
import com.apestech.framework.dictionary.DictUtil;
import com.apestech.framework.json.JSON;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.metadata.MetaData;
import com.apestech.framework.stream.callback.ReadRowHander;

/**
 * @author hup
 * @create 2018-08-16-16:23
 */
public class TableRowHander implements ReadRowHander {
    private SqlResultSet rs;
    private MetaData md;

    public TableRowHander(SqlResultSet rs, MetaData md){
        this.rs=rs;
        this.md=md;
    }

    @Override
    public String processRow(int index) throws Exception {
        String TABLE_NAME="";
        JSONObject m=rs.toRowJson();
        String NAME=m.getString("COLUMN_NAME");
        JSONObject map=DictUtil.getReslutData(NAME, m.getString("REMARKS"), m.getString("TYPE_NAME"),
                m.getString("COLUMN_DEF"), m.getString("NULLABLE"),
                m.get("CHAR_OCTET_LENGTH"), m.get("COLUMN_SIZE"),
                m.get("DECIMAL_DIGITS"));

        String ktxt="";
        String tab=rs.getString("TABLE_NAME");
        if(!TABLE_NAME.equals(tab)){
            JSONObject key=md.getTableKey(tab);
            if(key.size()>0){
                key.put("TABLE_NAME", tab);
                ktxt="PRIMARY:"+ JSON.toJSONString(key)+"\n";
            }
            key=md.getImportedKey(tab);
            if(key.size()>0){
                ktxt=ktxt+"IMPORTED:"+JSON.toJSONString(key)+"\n";
            }
        }
        map.put("TABLE_NAME", tab);
        String txt=ktxt+JSON.toJSONString(map);
        return txt;
    }
}
